package ru.susu.algebra.chartable.constructor;

import java.util.HashMap;

import ru.susu.algebra.chartable.IPermutationsGroupCharTable;
import ru.susu.algebra.partition.Partition;

/**
 * @author akargapolov
 * @since: 01.03.2009
 */
public abstract class PermGroupTableConstructorBase<T> implements IPermCharTableConstructor<T>
{
	private HashMap<Integer, IPermutationsGroupCharTable<T>> _tables = new HashMap<Integer, IPermutationsGroupCharTable<T>>();

	@Override
	public T getValue(Partition p1, Partition p2) throws Exception
	{
		IPermutationsGroupCharTable<T> table = this.getTable(p1);
		T value = table.getCharacter(p1, p2);
		if (value == null)
		{
			value = this.calcValue(p1, p2);
			table.setCharacter(p1, p2, value);
		}
		return value;
	}

	private IPermutationsGroupCharTable<T> getTable(Partition p)
	{
		int sum = p.getPresentedNumber();
		if (!_tables.containsKey(sum))
		{
			_tables.put(sum, this.createTable(p));
		}
		return _tables.get(sum);
	}

	protected abstract IPermutationsGroupCharTable<T> createTable(Partition p);

	public abstract T calcValue(Partition p1, Partition p2) throws Exception;

}
